/******************************************************************************
@file:  AccountLogin.java
@author Ramesh Anandhan
DESCRIPTION
    Acivity displays login widgets.
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
******************************************************************************/

package com.smartc.ui;

import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.smartc.connection.LoginHandler;
import com.smartc.connection.ParsedLoginData;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/*
 * AccountLogin.java
 * displays login widgets
 * runs https connection query for login
 */
public class AccountLogin extends Activity implements TextWatcher{
	
	private final String TAG = "AccountLogin";
	public static final boolean DEBUG = true;
	private final int PROGRESS_DIALOG = 0x01;
	
	private EditText mUsrname = null;
	private EditText mPassword = null;
	private Button mLogin = null;
	private ProgressDialog mDialog = null;
	
	
	private ParsedLoginData mParsedlogindata;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_login);
        
        mUsrname = (EditText) findViewById(R.id.user_name);
        mPassword = (EditText) findViewById(R.id.password);
        mLogin = (Button) findViewById(R.id.login);
        mLogin.setEnabled(false);
        mUsrname.addTextChangedListener(this);
        mPassword.addTextChangedListener(this);
        mLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if(DEBUG) Log.d(TAG, "onClick()");
				//display progress note
				showDialog(PROGRESS_DIALOG);				
				Thread thread = new Thread(){
					@Override
					public void run() {
						//start login http connection
						tryLogin();
					}
				};
				thread.start();
			}
		});
    }

	@Override
	protected void onResume() {
		super.onResume();
		validateFields();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		if(id == PROGRESS_DIALOG){
			mDialog = new ProgressDialog(this);
			mDialog.setMessage(getResources().getString(R.string.connectin_progress));
			mDialog.setIndeterminate(true);
			mDialog.setCancelable(true);
			return mDialog;
		}
		return super.onCreateDialog(id);
	}

	/*
	 * validates the input fields(username & password)
	 */
	private void validateFields(){
		boolean isvalid = isFieldValid(mUsrname) && isFieldValid(mPassword);
		mLogin.setEnabled(isvalid);
	}
	
	private boolean isFieldValid(TextView view){
		return view.getText()!= null && view.getText().length() > 0;
	}

	@Override
	public void afterTextChanged(Editable s) {
		validateFields();
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		
	}
	
	/*
	 * tries https connection and post the reponse to main thread
	 */
	private void tryLogin(){
		String username = mUsrname.getText().toString().trim();
		String password = mPassword.getText().toString().trim();
		if(DEBUG) Log.d(TAG, "onClick() username:"+username+", password:"+password);
		
		DefaultHttpClient http_client = new DefaultHttpClient();
		
		String domain = getResources().getString(R.string.domain);
		String login = getResources().getString(R.string.logins);
		String login_url = domain+login;
		HttpPost http_post = new HttpPost(login_url);
		ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
		//adds username & passward for query
		nvps.add(new BasicNameValuePair("username",username));
		nvps.add(new BasicNameValuePair("password",password));
		
		try{
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
			http_post.setEntity(entity);
			HttpResponse response = http_client.execute(http_post);
			HttpEntity responseEntity = response.getEntity();
			
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			
			LoginHandler myloginHandler = new LoginHandler();
			xr.setContentHandler(myloginHandler);
			xr.parse(retrieveInputStream(responseEntity));
			
			mParsedlogindata = myloginHandler.getParsedLoginData();
			if(DEBUG) Log.e(TAG,"tryLogin() mIdUser:"+ParsedLoginData.mIdUser);
			if(mParsedlogindata.getStatus().equals("SUCCESS")){
				if(DEBUG) Log.e(TAG,"tryLogin(): SUCCESS");
                Message myMessage=new Message();
                myMessage.obj="SUCCESS";
                handler.sendMessage(myMessage); 
			}
			else if(mParsedlogindata.getStatus().equals("ERROR")){
				if(DEBUG) Log.e(TAG,"tryLogin(): ERROR");
                Message myMessage=new Message();
                myMessage.obj="ERROR";
                handler.sendMessage(myMessage); 
			}
			
		}catch (Exception e) {
			if(DEBUG) Log.e(TAG,"tryLogin(): "+e.toString());
			e.printStackTrace();
			removeDialog(PROGRESS_DIALOG);
		}
	}

	private InputSource retrieveInputStream(HttpEntity responseEntity) {
		InputSource insrc = null;
		try{
			insrc = new InputSource(responseEntity.getContent());
		}catch (Exception e) {
			Log.e(TAG,"retrieveInputStream(): "+e.toString());
			e.printStackTrace();
		}
		return insrc;
	}
	
	/*
	 * worker thread post reponse on this handler
	 * runs in UI thread
	 */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
              String loginmsg=(String)msg.obj;
              if(loginmsg.equals("ERROR")) {
            	   //login failed - display error note
                    removeDialog(PROGRESS_DIALOG);
    				AlertDialog.Builder builder = new AlertDialog.Builder(AccountLogin.this);
    				builder.setMessage(mParsedlogindata.getMessage());
    				builder.setPositiveButton(getResources().getString(R.string.ok), null);
    				builder.create().show();
              }else if(loginmsg.equals("SUCCESS")){
            	    //login successful - diaply home screen & finish login activity
					Intent intent = new Intent();
					intent.setClass(AccountLogin.this, GeekHomeScreen.class);
					startActivity(intent);
					removeDialog(PROGRESS_DIALOG);
					finish();
              }
        }
  }; 
}